<template>
    <div class="script-data">
        <Poptip
            confirm
            :title="title"
            @on-ok="showModal"
            transfer 
            word-wrap 
            :width="width" >
            <Button :type="btnType" :disabled="disabled" title="大屏脚本数据" :ghost="ghost"
                :class="{'hidden-border': hiddenBorder, 'disabled': disabled, 'not-disabled': (!disabled && isButton)}">
                <Icon type="md-desktop" :size="iconSize" :style="{ color: iconColor }"/> {{btnText}}
            </Button>
        </Poptip>
        <Modal
            v-model="isShow"
            title="大屏脚本数据"
            :footer-hide="true"
            :width="900"
            class="my-modal"
            :mask-closable="false">
            <Row :gutter="16">
                <Col span="18">
                    <Form ref="formInline" :model="formData" :rules="ruleInline" :label-width="80">
                        <div v-for="(item, index) in formData.items" :key="item.key">
                            <FormItem :label="`第${index + 1}步`">
                                <Row>
                                    <Col span="6">
                                        <FormItem prop="src">
                                            <Select filterable clearable v-model="item.src" transfer placeholder="请选择源">
                                                <Option v-for="(subItem, subIndex) in desPositions" :key="subIndex" 
                                                    :value="subItem.id">{{subItem.name}}</Option>
                                            </Select>
                                        </FormItem>
                                    </Col>
                                    <Col span="1" style="text-align: center">-</Col>
                                    <Col span="6">
                                        <FormItem prop="target">
                                            <Select filterable clearable v-model="item.target" transfer placeholder="请选择目标">
                                                <Option v-for="(subItem, subIndex) in desPositions" :key="subIndex" 
                                                    :value="subItem.id">{{subItem.name}}</Option>
                                            </Select>
                                        </FormItem>
                                    </Col>
                                    <Col span="6" offset="1">
                                        <FormItem prop="desPosition">
                                            <Select filterable clearable v-model="item.desPosition" transfer placeholder="请选择展示方">
                                                <Option value="src">源</Option>
                                                <Option value="target">目的</Option>
                                            </Select>
                                        </FormItem>
                                    </Col>
                                    <Col span="3" offset="1">
                                        <Poptip
                                            confirm
                                            :title="`确定要删除第${index + 1}步吗？`"
                                            @on-ok="handleRemove(index)"
                                            transfer
                                            class="my-poptip"
                                            word-wrap>
                                            <Button type="error" long :disabled="(formData.items.length === 1)">删除</Button>
                                        </Poptip>
                                    </Col>
                                </Row>
                            </FormItem>
                            <Row>
                                <Col span="8">
                                    <FormItem label="展示范围" 
                                        :prop="'items.'+index+'.overAll'"
                                        :rules="[{required: true, type: 'number', message:'请选择展示范围', trigger: 'change'}]">
                                        <RadioGroup v-model="item.overAll">
                                            <Radio :label="0">局部</Radio>
                                            <Radio :label="1">全局</Radio>
                                        </RadioGroup>
                                    </FormItem>
                                </Col>
                                <Col span="8">
                                    <FormItem label="攻击结果" 
                                        :prop="'items.'+index+'.result'">
                                        <Select filterable v-model="item.result" transfer clearable placeholder="" style="width: 110px;">
                                            <Option :value="0">失败</Option>
                                            <Option :value="1">植入成功</Option>
                                            <Option :value="2">最终成功</Option>
                                        </Select>
                                    </FormItem>
                                </Col>
                                <Col span="8">
                                    <FormItem label="展示时长（秒）" 
                                        :label-width="110"
                                        :prop="'items.'+index+'.duration'"
                                        :rules="[
                                            {required: true, type: 'number', message:'请输入展示时长', trigger: 'change'},
                                            {
                                                validator: (rule, value, callback) => {
                                                    if (!Number.isInteger(value)) {
                                                        callback('请输入整数')
                                                        return
                                                    }
                                                    if (value < 1 || value > 100) {
                                                        callback('范围: 1~100')
                                                        return
                                                    }
                                                    callback()
                                                }
                                            }
                                        ]">
                                        <InputNumber 
                                            v-model="item.duration" 
                                            :min="1" 
                                            :max="100" 
                                            style="width: 100%;"
                                            placeholder="范围: 1~100"></InputNumber>
                                    </FormItem>
                                </Col>
                            </Row>
                            <FormItem label="描述" prop="des">
                                <Input v-model.trim="item.des" type="textarea" :maxlength="1000" :autosize="{minRows: 2,maxRows: 5}"></Input>
                            </FormItem>
                        </div>
                    </Form>
                    <Button type="dashed" long @click="handleAdd" class="md-add-jh" style="margin-top: 24px;">创建步骤</Button>
                    <div style="display: flex; justify-content: flex-end; margin-top: 24px;">
                        <Button @click="(isShow = false)" style="margin-right: 8px">取消</Button>
                        <Button type="primary" @click="handleSubmit">发送数据</Button>
                    </div>
                </Col>
                <Col span="6">
                    <Upload  
                        style="width: 206px;"
                        :before-upload="getFileContent"
                        :show-upload-list="false"
                        action="//jsonplaceholder.typicode.com/posts/">
                        <Button long style="width: 164px;">导入JSON文件</Button>
                        <Tooltip class="too" style="margin-left: 10px;" :transfer='true' max-width="240" content="导入数据将覆盖表单内容，请确认表单数据已发送" placement="top">
                            <Icon type="ios-alert" class="ios-alert" />
                        </Tooltip>
                    </Upload>
                    <Button long @click="exportJson" style="margin-top: 20px; width: 164px;">导出JSON文件</Button>
                </Col>
            </Row>
        </Modal>
    </div>    
</template>

<script>
import { triggerEffect } from '@/api/drill_compete'

export default {
    name: 'ScriptData',
    props: {
        hiddenBorder: {
            type: Boolean,
            default: false
        },
        isButton: {
            type: Boolean,
            default: true
        },
        disabled: {
            type: Boolean,
            default: false
        },
        title: {
            type: String,
            default: '设置脚本数据，可以在定制可视化页面查看对应的效果。'
        },
        width: {
            type: Number,
            default: 250
        },
        projectId: {
            type: String,
            default: ''
        },
        btnType: {
            type: String,
            default: 'primary'
        },
        btnText: {
            type: String,
            default: ''
        },
        size: {
            type: String,
            default: 'default'
        },
        iconSize: {
            type: Number,
            default: 12
        },
        iconColor: {
            type: String,
            default: '#FFFFFF'
        },
        ghost: {
            type: Boolean,
            default: false
        }
    },
    watch: {
        isShow(newVal) {
            this.$nextTick(() => {
                if (!newVal) {
                    this.formData = {
                        items: [{
                            stepNum: '', 
                            overAll: 0, 
                            src: '', 
                            target: '', 
                            des: '', 
                            result: '', 
                            duration: 5,
                            desPosition: '',
                            key: (new Date().getTime() * Math.random())
                        }]
                    }
                }
                this.$refs.formInline.resetFields()
            })
        }
    },
    data() {
        return {
            ruleInline: {},
            isShow: false,
            desPositions: [
                {
                    id: 'police',
                    name: '公安'
                },
                {
                    id: 'illegalityNetwork',
                    name: '非法网站'
                },
                {
                    id: 'sideStation',
                    name: '旁站'
                }
            ],
            formData: {
                items: [{
                    stepNum: '', 
                    overAll: 0, 
                    src: '', 
                    target: '', 
                    des: '', 
                    result: '', 
                    duration: 5,
                    desPosition: '',
                    key: (new Date().getTime() * Math.random())
                }]
            }
        }
    },
    methods: {
        getFileContent(file){
            if(!file.name.endsWith('.json')){
                this.$Message.warning('请上传json文件')
                return false;
            }
            const reader = new FileReader();
            let _this = this
            reader.readAsText(file, "UTF-8")
            reader.onload = function(e){
                const fileString = e.target.result;
                const myData = JSON.parse(fileString);
                let list = []
                const formData = myData.map(item => {
                    let obj = {
                        stepNum: '', 
                        overAll: item.overAll || 0, 
                        src: item.src || '', 
                        target: item.target || '', 
                        des: item.des || '', 
                        result: (!item.result && item.result !== 0) ? '' : item.result, 
                        duration: item.duration || 5,
                        desPosition: item.desPosition || '',
                        key: (new Date().getTime() * Math.random())
                    }
                    list.push(obj)
                })
                _this.formData.items = list
            }
            return false;
        },
        showModal() {
            this.isShow = true
        },
        handleAdd() {
            this.formData.items.push({
                stepNum: '', 
                overAll: 0, 
                src: '', 
                target: '', 
                des: '', 
                result: '', 
                duration: 5,
                desPosition: '',
                key: (new Date().getTime() * Math.random())
            })
        },
        handleRemove(index) {
            this.formData.items.splice(index, 1)
        },
        handleSubmit() {
            this.$refs.formInline.validate(valid => {
                let param = this.formData.items.map((item, index) => {
                    item.stepNum = index + 1
                    return item
                })
                if (valid) {
                    triggerEffect(this.projectId, JSON.stringify(param)).then(({ code, message }) => {
                        if (code !== 1) {
                            this.$Message.warning(message);
                            return
                        }
                        this.$Message.success('脚本数据发送成功');
                        this.isShow = false
                    })
                } else {
                    this.$Message.warning('请完善表单')
                }
            })
        },
        exportJson() {
            this.$refs.formInline.validate(valid => {
                let param = this.formData.items.map((item, index) => {
                    item.stepNum = index + 1
                    return item
                })
                if (valid) {
                    
                    let str = JSON.stringify(param)
                    const url = URL.createObjectURL(new Blob(str.split('')))
                    this.download(url, '大屏脚本数据.json')
                } else {
                    this.$Message.warning('请完善表单')
                }
            })
        },
        download (url, name) {
            const a = document.createElement('a')
            a.download = name
            a.rel = 'noopener'
            a.href = url
            // 触发模拟点击
            a.dispatchEvent(new MouseEvent('click'))
        }
    },
}
</script>

<style scoped>
.script-data /deep/ .ivu-poptip,
.script-data /deep/ .ivu-poptip-rel {
    width: 100%;
}
.hidden-border {
    border: none;
    background: none;
    box-shadow: none;
}

.disabled /deep/ i {
    color: #7D7F92 !important;
}

.not-disabled /deep/ i {
    color: #ffffff !important;
}

.my-modal /deep/ .ivu-modal .ivu-modal-content .ivu-modal-body .ivu-form {
    height: fit-content;
    max-height: calc(100vh - 356px);
    min-height: 166px;
    overflow: auto;
}

.my-modal /deep/ .ivu-modal .ivu-modal-content .ivu-modal-body .ivu-form > div:last-child > .ivu-form-item:last-child {
    margin-bottom: 0;
}

.my-poptip,
.my-poptip /deep/ .ivu-poptip-rel {
    width: 100%;
}

.ios-alert {
    color: orange;
    font-size: 16px;
    cursor: pointer;
}
</style>